package com.iss.umservice.common.xml;

import java.util.LinkedList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * <p>
 * [���ܼ���]XML�����¼�������
 * <p>
 * <p>
 * [��ϸ����]XML�����¼�������
 * </p>
 * @author  gcxu
 * @version  [GZT 1.00, Aug 19, 2010]
 * @see  [�����/����]
 * @since  [GZT]
 */
public class XmlHandler extends DefaultHandler
{
    /** ��ڵ� */
    private XmlNode rootNode = new XmlNode();
    
    /** ����ջ */
    private LinkedList<XmlNode> stack = new LinkedList<XmlNode>();
    
    /** ��ǰֵ */
    private StringBuffer currentValue = new StringBuffer(128);
    
    /**
     * ȡ��ڵ�
     * @return
     */
    public XmlNode getRootNode()
    {
        return rootNode;
    }
    
    /**
     * ��ʼ����ĳԪ��
     * @param uri       Ԫ�ص���ռ�
     * @param localName Ԫ�صı�����
     * @param qName     Ԫ�����
     * @param attributes ���Ա�
     */
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException
    {
        XmlNode topNode = stack.isEmpty() ? rootNode : (new XmlNode());
        
        topNode.setName(qName);
        
        int len = attributes.getLength();
        if (len > 0)
        {
            for (int i = 0; i < len; i++)
            {
                topNode.setAttribute(attributes.getQName(i),
                        attributes.getValue(i));
            }
        }
        
        if (!stack.isEmpty())
        {
            topNode.setParent((XmlNode)stack.get(0));
        }
        
        stack.addFirst(topNode);
    }
    
    /**
     * �������ĳԪ��
     * @param uri       Ԫ�ص���ռ�
     * @param localName Ԫ�صı�����
     * @param qName     Ԫ�����
     */
    public void endElement(String uri, String localName, String qName)
            throws SAXException
    {
        XmlNode topNode = (XmlNode)stack.removeFirst();
        topNode.setValue(currentValue.toString().trim());
        currentValue.setLength(0);
        if (topNode.getParent() != null)
        {
            topNode.getParent().setValue(null);
        }
    }
    
    /**
     * ֵ����
     * @param ch        ���
     * @param start     ��ʼλ
     * @param length    ����
     */
    public void characters(char[] ch, int start, int length)
            throws SAXException
    {
        currentValue.append(ch, start, length);
    }
}